package com.elinkway.infinitemovies.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.elinkway.infinitemovies.adapter.TopicHomeListAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.AdDataBean;
import com.elinkway.infinitemovies.bean.TopicDataList;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.TopicDataParser;
import com.elinkway.infinitemovies.listener.MyOnRefreshListner;
import com.elinkway.infinitemovies.ui.activity.TopicDetailActivity;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.view.PublicLoadLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;

public class TopicFragment extends BaseFragment implements
        ListView.OnItemClickListener {
    public static final String TAG = "TopicFragment";

    private AdDataBean mTopicAdData;

    private PublicLoadLayout root;
    /**
     * The fragment's ListView/GridView.
     */
    private PullToRefreshListView mListView;

    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private TopicHomeListAdapter mAdapter;

    private TopicDataList topicDatas;
    private RequestTopicDataTask requestTask;
    private int currentPage = 1;
    private boolean hasMore = true;

    private int mTop = 0;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            mListView.onRefreshComplete();
            super.handleMessage(msg);
        }

    };

    // TODO: Rename and change types of parameters
    public static TopicFragment newInstance(int position) {
        TopicFragment fragment = new TopicFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public TopicFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");
        root = UIs.createPage(getActivity(), R.layout.fragment_topic);
        root.loading(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView");

        // Set the adapter
        mListView = (PullToRefreshListView) root
                .findViewById(R.id.topic_home_list);

        Rect frame = new Rect();
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int actionBarHeight = getSupportActionBar().getHeight();
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        lp.setMargins(0, actionBarHeight, 0, 0);
        mListView.setLayoutParams(lp);

        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        resetHasMore();
        mListView.setOnRefreshListener(new TopicOnRefreshListener());
        mListView.setOnScrollListener(new TopicOnScrollListener());

        Log.i(TAG, "onDisplay?");
        if (topicDatas == null) {
            requestTask = new RequestTopicDataTask(getActivity(), true,
                    true);
            requestTask.start();
        } else {
            root.finish();
        }

        return root;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        super.setFragmentClassName(TAG);
        Log.i(TAG, "onAttach");

    }

    @Override
    public void onDetach() {
        Log.i(TAG, "onDetach");
        super.onDetach();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        int clickPosition = position - 1;
        String themeid = topicDatas.getTopics().get(clickPosition).getThemeId();
        String name = topicDatas.getTopics().get(clickPosition).getName();
        UmengEventPoster.postThemeClick(name);
        TopicDetailActivity.launch(getActivity(), themeid, name);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            Log.i(TAG, "onDisplay?");
            MoviesApplication.getInstance().setLastPageClassName(TAG);
            if (topicDatas == null) {
                requestTask = new RequestTopicDataTask(getActivity(), true,
                        true);
                requestTask.start();
            } else {
                root.finish();
            }
            // 相当于Fragment的onResume
        } else {
            // 相当于Fragment的onPause
        }
    }

    private class RequestTopicDataTask extends
            MoviesHttpAsyncTask<TopicDataList> {

        private int requestPage;
        private boolean isRefresh = true;

        @Override
        public void netNull() {
            super.netNull();
            root.error(false, false);
            root.setmRefreshData(new PublicLoadLayout.RefreshData() {

                @Override
                public void refreshData() {
                    currentPage = 1;
                    if (requestTask != null) {
                        if (!requestTask.isCancelled()) {
                            requestTask.cancel();
                            requestTask = null;
                        }
                    }
                    requestTask = new RequestTopicDataTask(getActivity(), true,
                            true);
                    requestTask.start();
                }
            });

        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            root.error(false, false);
            root.setmRefreshData(new PublicLoadLayout.RefreshData() {

                @Override
                public void refreshData() {
                    currentPage = 1;
                    if (requestTask != null) {
                        if (!requestTask.isCancelled()) {
                            requestTask.cancel();
                            requestTask = null;
                        }
                    }
                    requestTask = new RequestTopicDataTask(getActivity(), true,
                            true);
                    requestTask.start();
                }
            });
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            root.error(false, false);
            root.setmRefreshData(new PublicLoadLayout.RefreshData() {

                @Override
                public void refreshData() {
                    currentPage = 1;
                    if (requestTask != null) {
                        if (!requestTask.isCancelled()) {
                            requestTask.cancel();
                            requestTask = null;
                        }
                    }
                    requestTask = new RequestTopicDataTask(getActivity(), true,
                            true);
                    requestTask.start();
                }
            });
        }

        public RequestTopicDataTask(Context context, Boolean needLoading,
                                    Boolean isRefresh) {
            super(context);
            requestPage = currentPage;
            this.isRefresh = isRefresh;
            if (needLoading) {
                root.loading(false);
            }
        }

        @Override
        public LVideoDataHull<TopicDataList> doInBackground() {
            return MoviesHttpApi.requestTopicData(requestPage,
                    MoviesConstant.TOPIC_REQUEST_SIZE, new TopicDataParser());
        }

        @Override
        public void onPostExecute(int updateId, TopicDataList result) {
            if (mAdapter == null) {
                topicDatas = result;
                // lihui3
                mAdapter = new TopicHomeListAdapter(getActivity()
                        , topicDatas);
                mListView.setAdapter(mAdapter);
            } else {
                if (!isRefresh) {
                    mAdapter.addItem_data(result);
                } else {
                    topicDatas = result;
                    mAdapter.setItem_data(topicDatas);
                    resetHasMore();
                }
                mAdapter.notifyDataSetChanged();
            }
            if (result.getTopics().size() == MoviesConstant.TOPIC_REQUEST_SIZE) {
                currentPage += 1;
            } else {
                setNoMore();
            }
            mListView.onRefreshComplete();
            root.finish();
        }

    }

    private class TopicOnRefreshListener extends MyOnRefreshListner {

        @Override
        protected void onLoadMoreData() {
            if (hasMore) {
                if (requestTask != null) {
                    if (!requestTask.isCancelled()) {
                        requestTask.cancel();
                        requestTask = null;
                    }
                }
                requestTask = new RequestTopicDataTask(getActivity(), false,
                        false);
                requestTask.start();
            } else {
                handler.sendEmptyMessageDelayed(0, 50);
            }
        }

        @Override
        protected void onRefreshData() {
            currentPage = 1;
            if (requestTask != null) {
                if (!requestTask.isCancelled()) {
                    requestTask.cancel();
                    requestTask = null;
                }
            }
            requestTask = new RequestTopicDataTask(getActivity(), false, true);
            requestTask.start();
        }

    }

    @SuppressWarnings("deprecation")
    private void setNoMore() {
        hasMore = false;
        mListView.setLoadingDrawable(
                getResources().getDrawable(R.drawable.transparent),
                Mode.PULL_UP_TO_REFRESH);
        mListView.setRefreshingLabel(getString(R.string.havenomore),
                Mode.PULL_UP_TO_REFRESH);
        mListView.setReleaseLabel(getString(R.string.havenomore),
                Mode.PULL_UP_TO_REFRESH);
        mListView.setPullLabel(getString(R.string.havenomore),
                Mode.PULL_UP_TO_REFRESH);
    }

    private void resetHasMore() {
        hasMore = true;
        mListView.setLoadingDrawable(
                getResources().getDrawable(R.drawable.default_ptr_rotate),
                Mode.PULL_UP_TO_REFRESH);
        mListView.setRefreshingLabel(getString(R.string.loading),
                Mode.PULL_UP_TO_REFRESH);
        mListView.setReleaseLabel(getString(R.string.release_loadmore),
                Mode.PULL_UP_TO_REFRESH);
        mListView.setPullLabel(getString(R.string.pull_loadmore),
                Mode.PULL_UP_TO_REFRESH);
    }

    private class TopicOnScrollListener implements AbsListView.OnScrollListener {

        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if(mAdapter != null && mListView != null){
                int top = 0;
                int allHeight = mListView.getHeight();
                if(absListView.getChildAt(1) != null){
                    int height = absListView.getChildAt(1).getHeight();
                    top = - absListView.getChildAt(1).getTop()+ firstVisibleItem*height;
                }

                if(mTop == top || allHeight == 0){
                    return;
                }else{
                    for(int i = 1; i < visibleItemCount; i++){
                        if(absListView.getChildAt(i) != null && absListView.getChildAt(i).findViewById(R.id.img_topic_home_list_cover) != null) {
                            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 0);
                            int marginTop = absListView.getChildAt(i).getTop();
                            int relaMargin = (marginTop*UIs.dipToPx(20))/allHeight;
                            params.topMargin = -relaMargin;
                            params.bottomMargin = relaMargin - UIs.dipToPx(20);
                            if (params.topMargin < -UIs.dipToPx(20)) {
                                params.topMargin = -UIs.dipToPx(20);
                            } else if (params.topMargin > 0) {
                                params.topMargin = 0;
                            }
                            if (params.bottomMargin < -UIs.dipToPx(20)) {
                                params.bottomMargin = -UIs.dipToPx(20);
                            } else if (params.bottomMargin > 0) {
                                params.bottomMargin = 0;
                            }
                            absListView.getChildAt(i).findViewById(R.id.img_topic_home_list_cover).setLayoutParams(params);
                        }
                    }
                    mTop = top;
                }
            }
        }
    }
}
